<template>
  <div>
    <div class="vpc-network-network-search">
      <el-button
          class="search-wrapper-button"
          type="primary"
          @click="addApiConfig"
      >新 建</el-button>
      <div class="vm-manage-search">
<!--        <el-input-->
<!--            v-model="keyword"-->
<!--            placeholder="请输入搜索内容"-->
<!--            clearable-->
<!--            @input="getAPIConfigByVpcData"-->
<!--        />-->
      </div>
    </div>
    <div class="vpc-network-table content-wrapper el-card el-card__body is-always-shadow">
      <TableComponent
          ref="tableRef"
          :table-list="state.tableData"
          :table-column-info="apiConfigByVPC"
          @updateData="setPageInfo"
          :options-button="optionsButton"
          :options-width="160"
          @defaultPageData="setDefaultPage"
      >
        <template #status="{ data: { generate, status } }">
          <el-tag :type="generate ? (status ? 'success': 'primary') : 'info'"  v-text="generate ? (status ? '已配置': '未配置') : '未生成'"></el-tag>
        </template>
        <template #ipAllocationMode="{ data: { ipAllocationMode } }">
          <span>{{ ipAllocationMode === 1 ? 'dhcp' : 'static' }}</span>
        </template>
        <template #ipV4="{ data: { ipV4, netmask } }">
          <span>{{ netmask ? ipV4 + '/' + netmask : ipV4 }}</span>
        </template>

        <template #networkName="{ data: { ID, networkName, newNetworkName } }">
          <div class="flex items-center flex-col -space-y-1">
            <span v-if="networkName" v-text="networkName"/>
            <span
                v-if="newNetworkName !== networkName"
                class="updateData"
                v-text="`(${newNetworkName})`"
            />
          </div>
        </template>
        <template #conType="{ data: { ID, conType, newConType } }">
          <div class="flex items-center flex-col -space-y-1">
            <span v-if="conType" v-text="(conTypeObj[conType] )"/>
            <span
                v-if="newConType !== conType"
                class="updateData"
                v-text="`(${ conTypeObj[newConType] ? conTypeObj[newConType] : '' })`"
            />
          </div>
        </template>
      </TableComponent>
    </div>

    <el-dialog v-model="visible" :title="isAddStr === 'add' ? '新建' : '编辑'" class="add-vpc-api-dialog">
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          class="mt-1 m-1"
          label-position="right"
      >
        <el-form-item  label="网卡名称" prop="name" v-if="isAddStr === 'edit'">
          <el-input v-model.trim="form.name" disabled/>
        </el-form-item>
        <el-form-item label="网络类型" prop="ipAllocationMode">
          <el-select filterable v-model="form.ipAllocationMode">
            <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.ipAllocationMode === 0" label="IP" prop="ipV4">
          <el-input
              v-model.trim="form.ipV4"
              placeholder="请按照0.0.0.0格式填写"
          />
        </el-form-item>
        <el-form-item v-if="form.ipAllocationMode === 0" label="掩码" prop="netmask">
          <el-input-number v-model.number="form.netmask" :min="8" :max="32" :key="isAddStr + '_netmask'"/>
        </el-form-item>
        <el-form-item
            v-if="form.ipAllocationMode === 0"
            label="网关"
            prop="ipV4gateway"
        >
          <el-input v-model.trim="form.ipV4Gateway" />
        </el-form-item>
        <el-form-item  label="vlanTag" prop="vlan">
          <el-checkbox v-model="isCheckbox"  name="tag" @change="vlanTagChange" style="margin-top: 4px; display: inline-block"></el-checkbox>
          <el-input-number
              class="api-config-vlan-tag"
              v-model.number="form.vlanTag"
              min="2"  max="4095"
              v-if="isCheckbox"/>
        </el-form-item>
        <el-form-item  label="桥接网络" prop="conTypeCheck">
          <el-checkbox  v-model="isCheckboxConType" name="tag" @change="conTypeCheck" style="margin-top: 4px; display: inline-block"></el-checkbox>
        </el-form-item>
        <el-form-item label="桥接类型" prop="conType" v-if="isCheckboxConType">
          <el-radio-group
              v-model.number="form.conType"
              @change="conTypeChange">
            <el-radio-button label="VPC网络" :value="1" />
            <el-radio-button label="沙箱网络" :value="2" />
            <el-radio-button label="集群网络" :value="3" />
            <el-radio-button label="物理网卡" :value="4" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="桥接网络" prop="networkID" v-if="isCheckboxConType">
          <el-select
              v-if="form.conType === 1"
              filterable
              clearable
              v-model="form.networkID"
              style="width: 100%"
          >
            <el-option-group
                v-for="nets in netWorks"
                :key="nets.ID"
                :label="nets.name"
            >
              <el-option
                  v-for="net in nets.ports"
                  :key="net.ID"
                  :label="net.name"
                  :value="net.ID"
              />
            </el-option-group>
          </el-select>
          <el-select
              v-else
              v-model="form.networkID"
              class="w-full"
              filterable
              clearable
          >
            <el-option
                v-for="item in netWorks"
                :key="item.ID"
                :label="form.conType === 2 ? (item.ID + ':' + item.nickName) :item.name"
                :value="item.ID"
                :disabled="form.conType === 4 ? (item.status) : false"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span>
          <el-button @click="visible = false">取 消</el-button>
          <el-button type="primary" @click="addOrEditApiConfigData"> {{ isAddStr === 'add' ? '新 建' : '确 定' }} </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  onMounted,
  onUnmounted, reactive,
  ref,
  shallowReactive, shallowRef, watch,
} from 'vue';
import TableComponent from '@/components/table/TableComponent.vue';
import debounce from "lodash/debounce";
import { useRouter } from "vue-router";
import { apiConfigByVPC } from "@/views/simulation/defaultConfig";
import {setObjectValue, xtend} from "@/utils/common";
import {
  addApiConfigByVPCApi,
  delApiConfigByVPCApi,
  editApiConfigByVPCApi,
  getPortByVPCApi, getVpcListByClusterApi, getVPCListByComputedApi
} from "@/api/topo/simulationApi/vpc";
import {ElMessage, ElMessageBox} from "element-plus";
import {emitter} from "@/utils/bus";
import {allCount} from "@/layout/notification/service/service";
import {getSandboxListByComputedApi} from "@/api/topo/simulationApi/sandbox";
import {getVmToOverViewsApi} from "@/api/topo/simulationApi/docker";
import {getNodeInfo} from "@/api/topo/simulationApi/node";
import {get} from "@/api/topo/simulationApi/clusterNet";

// vpcID
const vpcID = ref('');

// 节点数据
const props = defineProps({
  vpcNode: null,
});

const router = useRouter();
const tableRef = ref(null);
const pageInfo = ref(null);
const keyword = ref('');
const state = shallowReactive({
  tableData: [],
});

// 表单
const isAddStr = ref('');
let editObj = {};
const visible = ref(false);
const formRef = ref(null);
const netWorks = shallowRef([]);
const form = reactive({
  name: '',
  ipV4: '',
  netmask: 24,
  ipV4Gateway: '',
  ipAllocationMode: 0,
  vlanTag: null,
  conType: 1,
  networkID: null
});
const isCheckbox = ref(false);
const isCheckboxConType = ref(false);

// 网络类型
const options = [
  {
    value: 0,
    label: 'static',
  },
  // {
  //   value: 1,
  //   label: 'dhcp',
  // },
];

const conTypeObj = {
  1: 'VPC网络',
  2: '沙箱网络',
  3: '集群网络',
  4: '物理网卡'
}

/**
 * 校验IP
 * @param rule
 * @param value
 * @param callback
 * @returns {*}
 */
const validateIP = (rule, value, callback) => {
  if (!value) return callback('IP不能为空');
  const par =
      /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/;
  if (!par.test(value)) return callback('请输入合法IP');
  return callback();
};

/**
 * 校验掩码
 * @param rule
 * @param value
 * @param callback
 * @returns {*}
 */
const validateMask = (rule, value, callback) => {
  if (!value) return callback('掩码不能为空');
  const masks = /^(?:[8-9]|[12]\d|3[0-2])$/;
  if (!masks.test(value)) {
    return callback('请输入合法掩码, 掩码范围8-32');
  }
  return callback();
};

/**
 * 校验网关
 * @param rule
 * @param value
 * @param callback
 * @returns {*}
 */
const validateGateWay = (rule, value, callback) => {
  if (!value) return callback();
  const par =
      /^((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.){3}(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])(?::(?:[0-9]|[1-9][0-9]{1,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5]))?$/;
  if (!par.test(value)) return callback('请输入合法网关');
  return callback();
};

const rules = {
  ipV4: [{ validator: validateIP, trigger: 'blur', required: true }],
  netmask: [{ validator: validateMask, trigger: 'blur', required: true }],
  ipV4gateway: [
    { validator: validateGateWay, trigger: 'blur', required: false },
  ],
  networkID: [{trigger: 'change', required: true, message: '请选择桥接网络'}]
};

const taskFunc = data => {
  const { msg } = data;
  const info = msg.update || msg.create;
  allCount.value = msg.count;

  // 判断是虚拟机当前页面操作且完成或者失败的操作
  if(info.name.indexOf('Vpc') !== -1) {
    if((info.status === 2 || info.status === 3)) {
      getAPIConfigByVpcData();
    }
  }
};
// 监听websocket消息通知
emitter.on('Task', taskFunc);

/**
 * 获取接口配置-VPC网络（防抖）
 * @type {DebouncedFuncLeading<(function(): Promise<void>)|*> | DebouncedFunc<(function(): Promise<void>)|*>}
 */
const getAPIConfigByVpcData = debounce(async() =>{
  return getPortByVPCApi(vpcID.value, {
    keyword: keyword.value,
  }).then(res => {
    if (!(res instanceof Error)) {
      tableRef.value?.setPageInfo({ total: res.data.length, page: 1, pageSize: 9999 });
      state.tableData = res.data;
    }
  });
}, import.meta.env.VITE_INPUT_DEBOUNCE_TIME);

// 初始化页数
const setDefaultPage = arg => (pageInfo.value = arg);

const setPageInfo = arg => {
  pageInfo.value = arg;
  getAPIConfigByVpcData();
};

const optionsButton = [
  {
    link: true,
    type: 'warning',
    name: '编辑',
    click: item => {
      visible.value = true;
      editObj = item;
      setObjectValue(form, item);
      isAddStr.value = 'edit';

      if(item.vlanTag) {
        isCheckbox.value = true;
      }

      if(item.conType) {
        isCheckboxConType.value = true;
        conTypeChange();
      }
    },
  },
  {
    link: true,
    type: 'danger',
    name: '删除',
    click: item => {
      ElMessageBox.confirm(
          `删除接口配置 【${item.name}】 ，删除后将不可恢复！`,
          '删除接口配置',
          {
            confirmButtonText: '删 除',
            cancelButtonText: '取 消',
            type: 'warning',
            center: true,
            customClass: 'delMessageBox',
            confirmButtonClass: 'delButtonClass',
          },
      ).then(async () => {
        editObj = item;
        isAddStr.value = 'del';
        delApiConfigByVPCApi(vpcID.value, item.ID).then(res => {
          if (!(res instanceof Error)) {
            ElMessage.success(`删除成功!`);

            if(!item.generate) {
              getAPIConfigByVpcData();
            }
          }
        });
      });
    },
  }
];

/**
 * 新建
 */
const addApiConfig = () =>{
  visible.value = true;
  isAddStr.value = 'add';
}

/**
 * 确认添加接口配置
 */
const addOrEditApiConfigData = () => {
  formRef.value?.validate(async valid => {
    if (valid) {
      if(!isCheckbox.value || !form.vlanTag) {
        form.vlanTag = 0;
      }

      if(!isCheckboxConType.value) {
        form.conType = 0;
      }

     if(isAddStr.value === 'add') {
       delete form['name'];
       addApiConfigByVPCApi(vpcID.value, form).then(res => {
         if (!(res instanceof Error)) {
           ElMessage.success('新建成功');
           visible.value = false;
         }
       });
     } else {
       editApiConfigByVPCApi(vpcID.value, editObj.ID,  form).then(res => {
         if (!(res instanceof Error)) {
           ElMessage.success('修改成功');
           visible.value = false;
           getAPIConfigByVpcData();
         }
       });
     }
    }
  });
};

/**
 * vlanTag默认不勾选是0，勾选是手填
 */
const vlanTagChange = (val) =>{
  isCheckbox.value = val;
  form.vlanTag = null;
}

/**
 * 桥接网络默认不勾选是0，勾选是选择
 * @param val
 */
const conTypeCheck = (val) =>{
  isCheckboxConType.value = val;

  if(val) {
    form.conType = 1;
    conTypeChange();
  } else {
    form.networkID = null;
  }
}

/**
 * 网卡类型修改
 */
const conTypeChange = () =>{
  getNetList();
}

/**
 * 获取桥接网络
 */
const getNetList = () => {
  if(isAddStr.value === 'add' || editObj.conType !== form.conType) {
    form.networkID = null;
  }

  netWorks.value = [];

  if(form.conType === 2) {
    getSandboxListByComputedApi(props.vpcNode.computerID, { page: 1, pageSize: 1000}).then(res => {
      if (!(res instanceof Error)) {
        const {
          data: { list },
        } = res;
        netWorks.value = list.filter(item => item.generate);
      }
    });
  } else if(form.conType === 1) {
    getVPCListByComputedApi(props.vpcNode.computerID, { page: 1, pageSize: 1000}).then(res => {
      if (!(res instanceof Error)) {
        let {
          data: { list },
        } = res;

        // 过滤未生成的和自己本身
        if(list && list.length > 0) {
          list = list.filter(item => {
            if(item.ID === props.vpcNode.ID) {
              return false;
            } else {
              if(item.ports && item.ports.length > 0) {
                item.ports = item.ports.filter(item => item.generate);
                return true;
              }
            }
          })
        }

        netWorks.value = list || [];
      }
    });
  } else if(form.conType === 3) {
    get(props.vpcNode.clusterID, { page: 1, pageSize: 9999 }).then(res => {
      if (!(res instanceof Error)) {
        const {
          data: { list },
        } = res;
        netWorks.value = list || [];
      }
    });
  } else if(form.conType === 4) {
    getNodeInfo(props.vpcNode.computerID).then(res => {
      if (!(res instanceof Error)) {

        // 过滤未占用的
        // if(res.data) {
        //   res.data.ComputerInterface = res.data.ComputerInterface.filter(item => !item.status)
        // }

        netWorks.value = res.data.ComputerInterface || [];
      }
    });
  }
};

// 监听传递过来的节点数据
watch(() =>props.vpcNode, (val) =>{
  vpcID.value = props.vpcNode.ID;

  if (vpcID.value) {
    getAPIConfigByVpcData();
  }
},  { immediate: true } )

watch(
    visible,
    () => {
      if (!visible.value) {
        formRef.value?.resetFields();
        setObjectValue(form, {
          name: '',
          ipV4: '',
          netmask: 24,
          ipV4Gateway: '',
          ipAllocationMode: 0,
          vlanTag: null,
          conType: 1,
          networkID: null
        })
        isCheckbox.value = false;
        isCheckboxConType.value = false;
      }
    },
    { immediate: false },
);

/**
 * 挂载-生命周期
 */
onMounted(() =>{
  getAPIConfigByVpcData();
});

/**
 * 卸载-生命周期（主要处理清除定时器、解绑操作）
 */
onUnmounted(() => {
  emitter.off('Task', taskFunc);
});
</script>
<style lang="scss" scoped>
.vpc-network-network-search {
  margin-top: 12px;
  position: relative;

  button {
    margin-left: 16px;
  }

  .vm-manage-search {
    top: -10px!important;
  }
}

.api-config-vlan-tag {
  display: inline-block;
  width: calc(100% - 35px);
  margin-left: 20px;
}

.vpc-network-table {
  padding-top: 12px;
  height: calc(100vh - 366px)!important;
}

:deep(.paginationclass) {
  display: none;
}

:deep(.updateData) {
  color: #ff0000;
}

:deep(.add-vpc-api-dialog) {
  width: 560px;
  .el-form {
    max-width: 460px;
    .el-form-item__label {
      width: 80px;
    }
  }
}
</style>
